<!DOCTYPE HTML>
<html>

<head>
   <meta charset="utf-8">
   <title>webSocket智能客服系统</title>
   <link rel="stylesheet" href="https://cdn.bootcss.com/twitter-bootstrap/3.4.1/css/bootstrap.min.css">
   <style>
      #chat-content {
         height: 240px;
         overflow-y: auto;
      }
      body{
         background:url('./images/bg.png') center;
         background-size: cover;
      }
      .container{
         width: 660px;
         margin-top: 30px;
      }
   </style>
</head>

<body>

   <div class="container">
      <!-- 聊天内容展示区域 -->
      <div class="well">
         <h4>聊天内容展示</h4>
         <hr>
         <div id="chat-content" class="clearfix">
         </div>
      </div>
      <div class="well">
         <div class="form-group">
            <input type="text" id="msg" class="form-control" placeholder="请输入聊天内容" autofocus
               onkeyup="keyupHandle(event)" />
         </div>
         <div class="form-group clearfix">
            <button class="btn btn-success" onclick="sendMsg()">发送消息</button>
         </div>
      </div>
   </div>

</body>
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
   if ("WebSocket" in window) {
      // 1-创建一个webscoket实例 http://106.13.182.88
      // var ws = new WebSocket("ws://106.13.182.88:8083");
      var ws = new WebSocket("ws://127.0.0.1:8083");
      // 2-打开一个socket通道
      ws.onopen = function () { ws.send(`msg=hi`); };
      // 点击按钮,发送消息
      function sendMsg() {
         // 获取用户输入的消息内容
         var msg = $("#msg").val().trim();
         if (msg == '') {
            $('#msg').focus();
            return false;
         }
         var html = `<div class="alert alert-warning"><strong>我:&nbsp;</strong>${msg}</div>`
         $("#chat-content").append(html);
         // 滚动到div#chat-content底部
         autoScroll();
         // 清空输入框内容
         $('#msg').val('');
         // 3-发送消息
         ws.send(`msg=${msg}`);
      }

      function keyupHandle(event) {
         if (event.keyCode == 13) {
            sendMsg();
         }
      }

      // 自动滚动到聊天内容底部

      function autoScroll() {
         // $('#chat-content').scrollTop($('#chat-content').outerHeight);
         var chat = $("#chat-content");
         chat.animate({ scrollTop: chat[0].scrollHeight - chat.height() }, 100)
      }



      // 4-监听服务端的响应
      ws.onmessage = function (event) {
         var html = `<div class="alert alert-success"><strong>她:&nbsp;</strong>${event.data}</div>`
         $("#chat-content").append(html);
         // 滚动到div#chat-content底部
         autoScroll();
      };

      // 5-监听websocket关闭
      ws.onclose = function () {
         // 关闭 websocket
         alert("连接已关闭...");
      };
   }

   else {
      // 浏览器不支持 WebSocket
      alert("您的浏览器不支持 WebSocket!");
   }
</script>

</html>